package com.efounder.view;

import android.app.Dialog;
import android.content.Context;
import androidx.databinding.DataBindingUtil;
import androidx.annotation.NonNull;
import androidx.annotation.StyleRes;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.bean.DetailsDatas;
import com.efounder.bean.GoodSkusBean;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.mobilemall.R;
import com.efounder.mobilemall.databinding.DialogProductSkuBinding;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.sku.OnSkuListener;
import com.pansoft.openplanet.util.TCMathUtil;

import java.util.List;

/**
 * Created by liufei on 2017/11/30.
 */
public class ProductSkuDialog extends Dialog {
    private DialogProductSkuBinding binding;
    private Context context;
    private DetailsDatas.GoodBean product;
    private List<GoodSkusBean> skuList;
    private Callback callback;
    private int skuType;

    private GoodSkusBean selectedSku;
    private boolean isTreasureGood;
    private String stockQuantityFormat;

    public ProductSkuDialog(@NonNull Context context) {
        this(context, R.style.CommonBottomDialogStyle);
    }

    public ProductSkuDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, themeResId);
        this.context = context;
        initView();
    }

    private void initView() {
        binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.dialog_product_sku, null, false);
        setContentView(binding.getRoot());

        binding.ibSkuClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        binding.btnSkuQuantityMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String quantity = binding.etSkuQuantityInput.getText().toString();
                if (TextUtils.isEmpty(quantity)) {
                    return;
                }
                int quantityInt = Integer.parseInt(quantity);
                if (quantityInt > 1) {
                    String newQuantity = String.valueOf(quantityInt - 1);
                    binding.etSkuQuantityInput.setText(newQuantity);
                    binding.etSkuQuantityInput.setSelection(newQuantity.length());
                    updateQuantityOperator(quantityInt - 1);
                }
            }
        });
        binding.btnSkuQuantityPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String quantity = binding.etSkuQuantityInput.getText().toString();
                if (TextUtils.isEmpty(quantity) || selectedSku == null) {
                    return;
                }
                int quantityInt = Integer.parseInt(quantity);
                if (quantityInt < selectedSku.getStockNumber()) {
                    String newQuantity = String.valueOf(quantityInt + 1);
                    binding.etSkuQuantityInput.setText(newQuantity);
                    binding.etSkuQuantityInput.setSelection(newQuantity.length());
                    updateQuantityOperator(quantityInt + 1);
                }
            }
        });
        binding.etSkuQuantityInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId != EditorInfo.IME_ACTION_DONE || selectedSku == null) {
                    return false;
                }
                String quantity = binding.etSkuQuantityInput.getText().toString();
                if (TextUtils.isEmpty(quantity)) {
                    return false;
                }
                int quantityInt = Integer.parseInt(quantity);
                if (quantityInt <= 1) {
                    binding.etSkuQuantityInput.setText("1");
                    binding.etSkuQuantityInput.setSelection(1);
                    updateQuantityOperator(1);
                } else if (quantityInt >= selectedSku.getStockNumber()) {
                    String newQuantity = String.valueOf(selectedSku.getStockNumber());
                    binding.etSkuQuantityInput.setText(newQuantity);
                    binding.etSkuQuantityInput.setSelection(newQuantity.length());
                    updateQuantityOperator(selectedSku.getStockNumber());
                } else {
                    binding.etSkuQuantityInput.setSelection(quantity.length());
                    updateQuantityOperator(quantityInt);
                }
                return false;
            }
        });
        binding.scrollSkuList.setListener(new OnSkuListener() {
            @Override
            public void onUnselected(GoodSkusBean.AttributeContentListBean unselectedAttribute) {
                selectedSku = null;
                LXGlideImageLoader.getInstance().displayRoundCornerImage(context, binding.ivSkuLogo, product.getGoodCover(), R.drawable.default_error, R.drawable.default_error, 20);
//                binding.tvSkuQuantity.setText(String.format(stockQuantityFormat, product.getStockQuantity()));
                String firstUnselectedAttributeName = binding.scrollSkuList.getFirstUnelectedAttributeName();
                binding.tvSkuInfo.setText(ResStringUtil.getString(R.string.mall_please_select) + firstUnselectedAttributeName);
                binding.btnSubmit.setEnabled(false);
                binding.btnBuy.setEnabled(false);
                binding.btnShopcart.setEnabled(false);
                binding.tvSkuSellingPrice.setText(TCMathUtil.retainAsignDecimalsWithZero(product.getMallGoodPrice().getPrice(), 2));
                String quantity = binding.etSkuQuantityInput.getText().toString();
                if (!TextUtils.isEmpty(quantity)) {
                    updateQuantityOperator(Integer.valueOf(quantity));
                } else {
                    updateQuantityOperator(0);
                }
            }

            @Override
            public void onSelect(GoodSkusBean.AttributeContentListBean selectAttribute) {
                String firstUnselectedAttributeName = binding.scrollSkuList.getFirstUnelectedAttributeName();
                binding.tvSkuInfo.setText(ResStringUtil.getString(R.string.mall_please_select) + firstUnselectedAttributeName);
            }

            @Override
            public void onSkuSelected(GoodSkusBean sku) {
                selectedSku = sku;
                LXGlideImageLoader.getInstance().displayRoundCornerImage(context, binding.ivSkuLogo, product.getGoodCover(), R.drawable.default_error, R.drawable.default_error, 20);
                List<GoodSkusBean.AttributeContentListBean> attributeList = selectedSku.getAttributeContentList();
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < attributeList.size(); i++) {
                    if (i != 0) {
                        builder.append("　");
                    }
                    GoodSkusBean.AttributeContentListBean attribute = attributeList.get(i);
                    builder.append("\"" + attribute.getVIdName() + "\"");
                }
                binding.tvSkuInfo.setText(ResStringUtil.getString(R.string.mall_selected) + builder.toString());
//                binding.tvSkuQuantity.setText(String.format(stockQuantityFormat, selectedSku.getStockNumber()));
                binding.tvSkuSellingPrice.setText(TCMathUtil.retainAsignDecimalsWithZero(selectedSku.getSkuPrice(), 2));
                binding.btnSubmit.setEnabled(true);
                if (skuType == 4 || skuType == 5) {
                    binding.btnSubmit.setEnabled(false);
                }
                binding.btnBuy.setEnabled(true);
                binding.btnShopcart.setEnabled(true);
                String quantity = binding.etSkuQuantityInput.getText().toString();
                if (!TextUtils.isEmpty(quantity)) {
                    updateQuantityOperator(Integer.valueOf(quantity));
                } else {
                    updateQuantityOperator(0);
                }
            }
        });
        binding.btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String quantity = binding.etSkuQuantityInput.getText().toString();
                if (TextUtils.isEmpty(quantity)) {
                    return;
                }
                int quantityInt = Integer.parseInt(quantity);
                if (quantityInt > 0 && quantityInt <= selectedSku.getStockNumber()) {
                    callback.onAdded(selectedSku, quantityInt);
                    dismiss();
                } else {
                    outOfStockHint(quantityInt);
                }
            }
        });
        //购物车回调
        binding.btnShopcart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String quantity = binding.etSkuQuantityInput.getText().toString();
                if (TextUtils.isEmpty(quantity)) {
                    return;
                }
                int quantityInt = Integer.parseInt(quantity);
                if (quantityInt > 0 && quantityInt <= selectedSku.getStockNumber()) {
                    callback.onAddToCart(selectedSku, quantityInt);
                    dismiss();
                } else {
                    outOfStockHint(quantityInt);
                }
            }
        });
        //立即购买回调
        binding.btnBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String quantity = binding.etSkuQuantityInput.getText().toString();
                if (TextUtils.isEmpty(quantity)) {
                    return;
                }
                int quantityInt = Integer.parseInt(quantity);
                if (quantityInt > 0 && quantityInt <= selectedSku.getStockNumber()) {
                    callback.onBuy(selectedSku, quantityInt);
                    dismiss();
                } else {
                    outOfStockHint(quantityInt);
                }
            }
        });
    }

    /**
     * 超出庫存，提示
     */
    private void outOfStockHint(int quantity) {
        Toast.makeText(getContext(), ResStringUtil.getString(R.string.mall_please_medify), Toast.LENGTH_SHORT).show();
        if (quantity < 1) {
            binding.etSkuQuantityInput.setText(String.valueOf(1));
        } else {
            binding.etSkuQuantityInput.setText(String.valueOf(selectedSku.getStockNumber()));
        }
        binding.etSkuQuantityInput.setSelection(String.valueOf(selectedSku.getStockNumber()).length());
    }

    /** 是否显示加入购物车及购买按钮 */
    public void setButton(int skuType) {
        this.skuType = skuType;
        if (skuType == 0) {
            binding.btnSubmit.setVisibility(View.GONE);
            binding.llCartBuy.setVisibility(View.VISIBLE);
        } else if (skuType == 1 || skuType == 3){
            binding.btnSubmit.setVisibility(View.VISIBLE);
            binding.llCartBuy.setVisibility(View.GONE);
            binding.btnSubmit.setBackground(context.getResources().getDrawable(R.drawable.comm_btn_red_selector));
            binding.btnSubmit.setText(R.string.mail_now_buy);
        } else if (skuType == 2) {
            binding.btnSubmit.setVisibility(View.VISIBLE);
            binding.llCartBuy.setVisibility(View.GONE);
            binding.btnSubmit.setBackground(context.getResources().getDrawable(R.drawable.comm_btn_blue_selector));
            binding.btnSubmit.setText(R.string.mail_join_shop_car);
        } else if (skuType == 4) {
            binding.btnSubmit.setVisibility(View.VISIBLE);
            binding.llCartBuy.setVisibility(View.GONE);
            binding.btnSubmit.setBackground(context.getResources().getDrawable(R.drawable.comm_btn_red_selector));
            binding.btnSubmit.setText(R.string.mall_not_start);
            binding.btnSubmit.setEnabled(false);
        } else if (skuType == 5) {
            binding.btnSubmit.setVisibility(View.VISIBLE);
            binding.llCartBuy.setVisibility(View.GONE);
            binding.btnSubmit.setBackground(context.getResources().getDrawable(R.drawable.comm_btn_red_selector));
            binding.btnSubmit.setText(R.string.mall_end);
            binding.btnSubmit.setEnabled(false);
        }
    }

    public void setData(final DetailsDatas.GoodBean product, GoodSkusBean selectedSku, boolean isTreasureGood, Callback callback) {
        this.product = product;
        this.skuList = product.getGoodSkus();
        this.selectedSku = selectedSku;
        this.callback = callback;
        this.isTreasureGood = isTreasureGood;

        if (isTreasureGood) {
            binding.scrollSkuList.setVisibility(View.GONE);
            binding.tvSkuInfo.setVisibility(View.GONE);
        } else {
            binding.scrollSkuList.setVisibility(View.VISIBLE);
            binding.tvSkuInfo.setVisibility(View.VISIBLE);
        }

        stockQuantityFormat = context.getString(R.string.product_detail_sku_stock);

        updateSkuData();
        binding.etSkuQuantityInput.setText("1");
        updateQuantityOperator(1);
    }

    private void updateSkuData() {
        binding.scrollSkuList.setSkuList(product.getGoodSkus());

        if (selectedSku != null) {
            initData();
        }else {
            GoodSkusBean firstSku = product.getGoodSkus().get(0);
            if (firstSku.getStockNumber() > 0) {
                selectedSku = firstSku;
                // 选中第一个sku
                initData();
            } else {
                LXGlideImageLoader.getInstance().displayRoundCornerImage(context, binding.ivSkuLogo, product.getGoodCover(), R.drawable.default_error, R.drawable.default_error, 20);
                binding.tvSkuSellingPrice.setText(TCMathUtil.retainAsignDecimalsWithZero(product.getMallGoodPrice().getPrice(), 2));
            binding.tvSkuSellingPriceUnit.setText(product.getMallGoodPrice().getPriceUnit());
//            binding.tvSkuQuantity.setText(String.format(stockQuantityFormat, product.getStockQuantity()));
                binding.btnSubmit.setEnabled(false);
                binding.btnBuy.setEnabled(false);
                binding.btnShopcart.setEnabled(false);
                binding.tvSkuInfo.setText(ResStringUtil.getString(R.string.mall_please_select) + skuList.get(0).getAttributeContentList().get(0).getPIdName());
            }
        }
    }

    private void initData() {
        binding.scrollSkuList.setSelectedSku(selectedSku);

        LXGlideImageLoader.getInstance().displayRoundCornerImage(context, binding.ivSkuLogo, product.getGoodCover(), R.drawable.default_error, R.drawable.default_error, 20);
        binding.tvSkuSellingPrice.setText(TCMathUtil.retainAsignDecimalsWithZero(selectedSku.getSkuPrice(), 2));
            binding.tvSkuSellingPriceUnit.setText(product.getMallGoodPrice().getPriceUnit());
//            binding.tvSkuQuantity.setText(String.format(stockQuantityFormat, selectedSku.getStockNumber()));
        binding.btnSubmit.setEnabled(selectedSku.getStockNumber() > 0);
        if (skuType == 4 || skuType == 5) {
            binding.btnSubmit.setEnabled(false);
        }
        binding.btnBuy.setEnabled(selectedSku.getStockNumber() > 0);
        binding.btnShopcart.setEnabled(selectedSku.getStockNumber() > 0);
        List<GoodSkusBean.AttributeContentListBean> attributeList = selectedSku.getAttributeContentList();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < attributeList.size(); i++) {
            if (i != 0) {
                builder.append("　");
            }
            GoodSkusBean.AttributeContentListBean attribute = attributeList.get(i);
            builder.append("\"" + attribute.getVIdName() + "\"");
        }
        binding.tvSkuInfo.setText(ResStringUtil.getString(R.string.mall_selected) + builder.toString());
//        if(product.getTypeBh().equals(GOOD_TYPE_VIRTUAL)){
//            binding.btnShopcart.setVisibility(View.GONE);
//        }
    }

    private void updateQuantityOperator(int newQuantity) {
        if (selectedSku == null) {
            binding.btnSkuQuantityMinus.setEnabled(false);
            binding.btnSkuQuantityPlus.setEnabled(false);
            binding.etSkuQuantityInput.setEnabled(false);
        } else {
            if (newQuantity <= 1) {
                binding.btnSkuQuantityMinus.setEnabled(false);
                binding.btnSkuQuantityPlus.setEnabled(true);
            } else if (newQuantity >= selectedSku.getStockNumber()) {
                binding.btnSkuQuantityMinus.setEnabled(true);
                binding.btnSkuQuantityPlus.setEnabled(false);
            } else {
                binding.btnSkuQuantityMinus.setEnabled(true);
                binding.btnSkuQuantityPlus.setEnabled(true);
            }
            binding.etSkuQuantityInput.setEnabled(true);
        }

    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        // 解决键盘遮挡输入框问题
        Window window = getWindow();
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        window.getDecorView().setPadding(0, 0, 0, 0);
       // KeyboardConflictCompat.assistWindow(getWindow());
//        AppUtils.transparencyBar(getWindow());
    }


    public interface Callback {
        void onAdded(GoodSkusBean sku, int quantity);

        void onBuy(GoodSkusBean skusBean, int quantity);

        void onAddToCart(GoodSkusBean skusBean, int quantity);
    }
}
